<template>
  <n-modal v-model:show="isVisible" title="添加采购计划" preset="dialog" @close="onClose" @update:show="onClose" style="height: 395px;width: 700px">
    <n-form @submit.prevent="handleSubmit" label-width="120px" class="form-container">
      <div class="form-row" style="margin-top: 20px">
        <n-form-item label="采购产品：" path="productId">
          <n-select v-model:value="form.productId"
                    placeholder="请选择产品"
                    :options="products"
                    style="width: 190px"
                    @update:value="handleProductChange"
          ></n-select>
        </n-form-item>
        <n-form-item label="入库仓库：" path="quantity" style="margin-left: 20px">
          <n-select
              v-model:value="form.storeId"
              :options="stores"
              style="width: 190px"
              clearable
              @update:value="handleStoreChange"
          ></n-select>
        </n-form-item>
        <n-form-item label="采购数量：" path="quantity" style="margin-left: 20px" :feedback="inventoryFeedback">
          <n-input v-model:value="form.quantity" placeholder="请输入采购数量" style="width: 190px" @update:value="handleQuantityChange"/>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="计划金额：" path="price">
          <n-input v-model:value="form.price" placeholder="请输入计划金额" style="width: 190px" disabled/>
        </n-form-item>
        <n-form-item label="计划时间：" path="time" style="margin-left: 20px">
          <n-date-picker
              v-model:formatted-value="time"
              placeholder="请选择计划时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              style="width: 190px"/>
        </n-form-item>
          <n-form-item label="负责人：" path="adminId" style="margin-left: 20px">
         <n-select
           v-model:value="form.adminId"
           :options="admins"
           style="width: 190px"></n-select>
        </n-form-item>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-row">
        <n-form-item>
          <n-button type="primary" native-type="submit" @click="handleSubmit">提交</n-button>
        </n-form-item>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>

import {onMounted, ref, watch} from 'vue';
import {useRouter} from 'vue-router';
import {useUserStore} from "@/store/index.js";
import api from '@/api/admin'
import {List} from "echarts";


const loading = ref(true)
const userStore = useUserStore()
const id = userStore.getId();
const router = useRouter()
const products = ref([])
const stores = ref([])
const admins = ref([])
const emit = defineEmits(['updatePage'])
const inventory = ref(null);
const props = defineProps({
  show: {
    type: Boolean,
    required: true,
  },
  onClose: {
    type: Function,
    required: true,
  },
  option: {
    type: List,
    require: true
  }
});
const statusOptions=ref([
  {
    label: '未通过',
    value:'未通过',
  },
  {
    label:'未进行',
    value: '未进行',
  },
  {
    label: '进行中',
    value: '进行中',
  },
  {
    label: '已完成',
    value: '已完成',
  }
])
const isVisible = ref(props.show);
watch(() => props.show, (newVal) => {
  isVisible.value = newVal;
});

const form = ref({
  productId: '',
  storeId: '',
  adminId: '',
  quantity: '',
  price: '',
  status: '待审核',
});
const time = ref(null)

const handleProductChange = (value) => {
  form.value.productId = value;
  checkInventory();
};

const handleStoreChange = (value) => {
	form.value.storeId = value;
	checkInventory();
};

const handleQuantityChange = async (value) => {
	form.value.quantity = value;
	try {
		const res = await api.findProduct({
      id: form.value.productId
		});
		const cost = parseFloat(res.data.cost) || 0; // 如果转换失败，则默认为0
		const quantity = parseFloat(value) || 0; // 如果转换失败，则默认为0
		form.value.price = (cost * quantity).toFixed(2);
	}
	catch (e) {
		$message.error(e);
	}
};

const checkInventory = async () => {
  if (form.value.productId && form.value.storeId) {
    await queryInventory();
  }
};
const queryInventory = async () => {
  try {
    const res = await api.findStoreCommodityByProductAndStoreId(
        {params: {storeId: form.value.storeId, productId: form.value.productId}}
    )
    if (res.code === 200) {
			if(res.data !== null) {
				inventory.value = res.data.quantity
      }
			else {
				inventory.value = 0;
      }
    } else {
      $message.error(res.message);
    }
  } catch (err) {
    $message.error("获取库存信息失败！");
  }
};
const inventoryFeedback = computed(() => {
  return inventory.value !== null ? `当前库存量：${inventory.value}` : '';
});

const handleSubmit = async () => {
  try {
    const planTime = time.value.toString()
    const res = await api.addPurchasePlan(
        {
          ...form.value,
          planTime: planTime,
          status: "待审核"
        }
    )
    if(res.code === 200) {
      emit("updatePage")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("添加采购计划失败！")
  }finally{
    clear()
    props.onClose();
  }
};

  const queryAdminList = async () => {
    loading.value = true
    try {
      const res = await api.findAdminByRole({
	      role: 'PURCHASEADMIN'
      })
      if(res.code === 200) {
        res.data.map((item)=>{
          admins.value.push({
            label: item.name,
            value: item.id
          })
        })
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取管理员信息失败！")
    }finally{
      loading.value = false
    }
  }
const queryStoreList = async () => {
  loading.value = true
  try {
    const res = await api.findAllStore()
    if(res.code === 200) {
      res.data.map((item)=>{
        stores.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库信息失败！")
  }finally{
    loading.value = false
  }
}
const queryProductList = async () => {
  loading.value = true
  try {
    const res = await api.findAllProduct()
    if(res.code === 200) {
      res.data.map((item)=>{
        products.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取产品信息失败！")
  }finally{
    loading.value = false
  }
}
const clear = () => {
  form.value.productId = null
  form.value.storeId = null
  form.value.adminId=null
  form.value.quantity=""
  form.value.price=""
  form.value.status=""
  time.value=null

}
onMounted(() => {
  queryStoreList()
  queryAdminList()
  queryProductList()
})
</script>
<style scoped>
  .form-container {
      display: flex;
      flex-direction: column;
      width: 100%;
      position: relative;
  }

  .form-row {
      display: flex;
      align-items: center;
      width: 100%;
  }

  .form-row > n-form-item {
      flex: 1;
  }

  .submit-row {
      justify-content: center;
      display: flex;
      width: 100%;
  }
</style>
